<?php


namespace app\admin\controller;


use app\common\model\HelpModel;
use think\facade\Request;
use think\Validate;

class HelpController extends BaseController {

    public function index() {
        return $this->fetch();
    }

    public function edit() {
        $id = Request::param('id', 0, 'intval');
        if ($id < 1) {
            return $this->error('未查询到相关数据');
        }
        $help_info = HelpModel::get($id);
        $type_cate = HelpModel::TYPE_CATE;

        $this->assign("type_cate", $type_cate);
        $this->assign('help_info', $help_info);
        return $this->fetch();
    }

    public function getlist() {
        $list = HelpModel::field('content', true)->select();
        if (count($list) > 0) {
            foreach ($list as &$item) {
                $item->type_txt = $item->type_text;
            }
            return self::bulidSuccess($list);
        }
        return self::bulidFail("未查询到相关数据");
    }

    public function edit_post() {
        $id        = Request::param('id', 0, 'intval');
        $all_param = Request::param();

        $validate = new Validate([
            'id'      => 'require|number',
            'title'   => 'require|length:2,32',
            'weight'  => 'require|number',
            'content' => 'require',
            'icon'    => 'require|url',
        ], [
            "id"      => "帮助文档信息不存在，请检查后在做编辑",
            "title"   => "标题在2-32个字符",
            "weight"  => "权重仅能输入数字",
            "content" => "请输入内容",
            "icon"    => "请上传图标",
        ]);

        if (!$validate->check($all_param)) {
            return self::bulidFail($validate->getError());
        }

        $help_info = HelpModel::get($id);
        if (empty($help_info)) {
            return self::bulidFail('帮助文档信息不存在');
        }

        // 查询标题是否已经存在
        $e_where     = [
            ['id', '<>', $id],
            ['title', '=', $all_param['title']]
        ];
        $help_exists = HelpModel::where($e_where)->field('id')->find();
        if (!empty($help_exists)) {
            return self::bulidFail('标题已经存在');
        }

        $help_info->title = $all_param['title'];
        $help_info->content = $all_param['content'];
        $help_info->type    = $all_param['type'];
        $help_info->icon    = $all_param['icon'];
        $help_info->weight  = $all_param['weight'];
        if ($help_info->save()) {
            // 记录日志
            $log_content = "编辑帮助文档，ID：{$help_info->id}，标题：{$help_info->title}";
            parent::addAdminLog($log_content);

            return self::bulidSuccess();
        }
        return self::bulidFail();
    }
}
